package com.zb.wx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zb.exception.WxException;
import com.zb.redis.RedisUtil;
import com.zb.service.ZjCustomerWxAuthorService;
import com.zb.service.impl.WxHttpClientUtil;
import com.zb.websocket.server.WxWebSocketServer;
import com.zb.wx.WxCacheKeyConstant;
import com.zb.wx.service.ConWxService;
import com.zb.wx.utils.WxSecureUtil;
import com.zb.wx.utils.WxXmlParseUtil;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author WEN
 * @Date 2024/3/1 0001
 **/
@Service
public class ConWxServiceImpl implements ConWxService {
    private static final Logger logger = LoggerFactory.getLogger(ConWxServiceImpl.class);
    @Resource
    private ZjCustomerWxAuthorService customerWxAuthorService;

    // 保存并缓存微信平台推送的票据
    @Override
    public void getWxThirdAuthorCallbackEvent(HttpServletRequest request) {
        logger.info("微信第三方授权回调事件：{}", request.getParameterMap());
        String xmlData = WxXmlParseUtil.getXmlDataFromRequest(request);
        if (StringUtils.isBlank(xmlData)) {
            return;
        }
        String decryptXmlData = WxSecureUtil.decrypt(request, xmlData);

        Map<String, String> resultMap = WxXmlParseUtil.xmlToMap(decryptXmlData);
        logger.info("微信第三方授权回调事件数据：{}", resultMap);
        String infoType = resultMap.get("InfoType");
        if (null == infoType) {
            return;
        }
        switch (infoType) {
            case "component_verify_ticket" -> {
                String componentVerifyTicket = resultMap.get("ComponentVerifyTicket");
                // 缓存票据
                RedisUtil.setCache(WxCacheKeyConstant.WX_COMPONENT_VERIFY_TICKET, componentVerifyTicket, WxCacheKeyConstant.WX_COMPONENT_VERIFY_TICKET_EXPIRE_TIME);
            }
            // 授权成功
            case "authorized" -> {
                // 已在 WxHttpClientUtil#createOpenAccountBindAuthorPubicNo 完成授权
            }
            // 解除授权
            case "unauthorized" -> {}
            // 商家更新了授权信息
            case "updateauthorized" -> {}
        }
    }

    // 微信授权后回调接口
    @Override
    public void getWxAuthorPubliNoMessageEventCallback(HttpServletRequest request) {
        logger.info("微信已授权公众号消息事件回调：{}", request.getParameterMap());
        String xmlData = WxXmlParseUtil.getXmlDataFromRequest(request);
        if (StringUtils.isBlank(xmlData)) {
            return;
        }
        String decryptXmlData = WxSecureUtil.decrypt(request, xmlData);

        Map<String, String> resultMap = WxXmlParseUtil.xmlToMap(decryptXmlData);
        logger.info("微信回调消息：{}", resultMap);
        String msgType = resultMap.get("MsgType");
        if (StringUtils.isBlank(msgType)) {
            return;
        }
        switch (msgType) {
            case "":
                break;
        }
    }

    // 微信授权成功重定向回调
    @Override
    public void getWxAuthorSuccessRedirectCallback(String authCode, Long expiresIn, String uuid) throws WxException {
        JSONObject objData = null;
        try {
            objData = WxHttpClientUtil.getQueryAuthCode(authCode);
        } catch (WxException e) {
            logger.error("获取授权信息异常：" + e);
            e.printStackTrace();
        }
        if (null == objData) {
            return;
        }
        // 获取缓存中的商家ID
        Long custAccId = (Long) RedisUtil.getByKey(WxCacheKeyConstant.WX_AUTHOR_WEBSOCKET_UUID + uuid);
        // 清除缓存中的商家ID
        RedisUtil.clearCache(WxCacheKeyConstant.WX_AUTHOR_WEBSOCKET_UUID + uuid);

        // 授权信息
        JSONObject authorizationInfo = JSON.parseObject(objData.getString("authorization_info"), JSONObject.class);
        String authorizerAccessToken = authorizationInfo.getString("authorizer_access_token"); // 接口调用令牌
        String authorizerAppid = authorizationInfo.getString("authorizer_appid");
        String authorizerRefreshToken = authorizationInfo.getString("authorizer_refresh_token");

        // 创建开放平台账号与公众号授权绑定
        String openAppId = WxHttpClientUtil.createOpenAccountBindAuthorPubicNo(authorizerAccessToken, authorizerAppid);
        if (null == openAppId) {
            openAppId = WxHttpClientUtil.getOpenAppid(custAccId);
        }
        // 缓存接口调用令牌
        Long authorizerAccessTokenExpiresIn = authorizationInfo.getLong("expires_in"); // authorizer_access_token 的有效期
        WxHttpClientUtil.setCacheAuthorizerAccessToken(custAccId, authorizerAccessToken, authorizerAccessTokenExpiresIn);

        customerWxAuthorService.save(custAccId, authorizerAppid, authorizerRefreshToken, openAppId);
        // 发送回调成功消息
        WxWebSocketServer.send(uuid);
    }
}
